﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Meraz.Core.Parsers
{
    public class TalkingPointsMemoParser : RegexBlogParser
    {
        string rawDateString;
        string alias;
        const string bylinePattern = @"<span class=""byline_text"">(?<ALIAS>.*?) \| (?<DATE>.*?)</span>";
        void ParseByline(string source)
        {
            Match match = Regex.Match(source, bylinePattern);
            if (!match.Success)
                return;
            alias = RemoveHtml(match.Groups["ALIAS"].Value);
            rawDateString = match.Groups["DATE"].Value;
        }

        internal override List<string> ParseAliases(string source)
        {
            if (string.IsNullOrWhiteSpace(alias))
                ParseByline(source);
            return new List<string> { alias };
        }

        internal override DateTime ParseDate(string source)
        {
            if (string.IsNullOrWhiteSpace(rawDateString))
                ParseByline(source);
            return DateTime.Parse(rawDateString);
        }

        internal override string ParseBody(string source)
        {
            string startMarker = @"<div class=""entry_text"">";
            int start = source.IndexOf(startMarker);
            if (start < 0)
                return null;
            start += startMarker.Length;
            int end = source.IndexOf(@"<!--", start);
            if (end < start)
                end = source.IndexOf(@"<h3 class=""subpost_related_hed", start);
            if (end < start)
                end = source.IndexOf(@"<div class=""mainblog_share_footer", start);
            return source.Substring(start, end - start);
        }
    }
}
